﻿// <copyright file="HandleFormTextBox.cs" company="Microsoft Corporation">
// Copyright (c) 2009 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-01-29</date>
// <summary>HandleFormTextBox class definition</summary>

namespace Microsoft.WebAnalytics.Behaviors.FormTrackers
{
    using System;
    using System.Windows.Controls;
    using Microsoft.WebAnalytics.Contracts;

    /// <summary>
    /// Handle the TextBox.TextChanged event for a form control
    /// </summary>
    [FormTracker(typeof(TextBox))]
    public class HandleFormTextBox : ITrackFormControl
    {
        #region Fields
        /// <summary>
        /// The event handler to track against
        /// </summary>
        private EventHandler<FormEventArgs> handler;
        #endregion

        #region ITrackFormControl Members

        /// <summary>
        /// Attach to the TextBox.TextChanged event
        /// </summary>
        /// <param name="control">a TextBox control</param>
        /// <param name="eventHandler">the Event handler to dispatch to</param>
        public void AttachEvents(Control control, EventHandler<FormEventArgs> eventHandler)
        {
            System.Diagnostics.Debug.Assert(control != null, "control cannot be null.");

            System.Diagnostics.Debug.Assert(eventHandler != null, "handler cannot be null.");

            this.handler = eventHandler;

            var textbox = control as TextBox;

            textbox.TextChanged += new TextChangedEventHandler(this.TextChanged);
        }

        /// <summary>
        /// Text changed event handler
        /// </summary>
        /// <param name="sender">the TextBox</param>
        /// <param name="e">the Text Changed Event arguments</param>
        private void TextChanged(object sender, TextChangedEventArgs e)
        {
            var formEvent = new FormEventArgs
            {
                Control = sender as Control,
                EventName = "TextChanged",
                InnerEvent = e
            };

            this.handler(this, formEvent);
        }

        #endregion
    }
}